#pragma once

#include <ros/ros.h>
#include <iostream>
#include <json/json.h>
#include <memory>

#include <boost/circular_buffer.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/thread.hpp>

#include "common_lib/socket_client_interface.h"
#include "common_lib/boost_circular_buffer.hpp"
#include "actuator/actuator.h"
#include "task/task_process.h"

namespace Communication
{
class SocketManger : public Socket::SocketClientInterface
{
public:
    SocketManger(ros::NodeHandle nh, ros::NodeHandle private_nh, const std::string ip, const unsigned short port);
    ~SocketManger();

    void OnConnectStatus(bool *isConnected, boost::system::error_code *ec);
    void ReadCallback(std::string *str_read, boost::system::error_code *ec);
    void HandleWrite(std::size_t *length, boost::system::error_code *ec);

    void Start(void);

private:
    ros::NodeHandle nh_;
    ros::NodeHandle private_nh_;

    bool server_is_connected_ = false;
    ros::Time time_start_connect_;

    Socket::BufferBound<std::string> recv_buffer_;
    Socket::BufferBound<std::string> send_buffer_;
    std::unique_ptr<actuator::ActuatorMain> ptr_actuator_;
    std::unique_ptr<task::TaskProcess> ptr_task_process_;
    
    AMRSendCmd amr_cmd_;  // 按照运动学模型解算每个电机的速度、角度
    AMRReceiveState amr_state_; // 按照反馈状态反算车体中心的速度、角速度

    ControlVelocity ctrl_velocity_;
    VehicleVelocity vehicle_velocity_;

    std::string param, log;

    std::unordered_map<uint64_t, std::string> umap_sn_cmd_record_;

    void TestRecvBuffer();

    void GetServoParams(std::string &param_file);
    void RecvDataHandle(void);
    void SendDataHandle(void);

    void ServoFeedbackParse(Json::Value &value);
    std::string TaskCmdParse(Json::Value &task_cmd);

    std::string JsonWriter(Json::Value &value);
};
}